/*
 * 太原科技大学。
 * Copyright 2021, YCHS Information&Science Technology Co.,Ltd,
 * All rights reserved.
 */
package com.itheima.interceptor;

//import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 定义拦截器
 * @author liuchao
 * @version 1.0
 * @date 2024/3/23
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源运行前运行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("运行前运行");
        //1、获取token
        String token=request.getHeader("token");
        //2、判断是否为空即未登录
        if (!StringUtils.hasLength(token)){//通过stringUtils判断，如果字符串不为null而且有长度则为真，这里加“！”判断不为真
            log.info("请求token为空，未登录");
            //返回错误信息和前端做对应
            Result error=Result.error("NOT_LOGIN");
            //强行手动转换josn格式给前端            这里导入阿里巴巴的fastjson模块
            String notLogin = JSONObject.toJSONString(error);
            //响应
            response.getWriter().write(notLogin);
            return false;
        }
        //3、解析token是否合法
        try {
            JWTUtils.getJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("非法token返回错误信息");
            //返回错误信息和前端做对应
            Result error=Result.error("NOT_LOGIN");
            //强行手动转换josn格式给前端            这里导入阿里巴巴的fastjson模块
            String notLogin = JSONObject.toJSONString(error);
            //响应
            response.getWriter().write(notLogin);
            return false;
        }

        //4、放行
        log.info("放行");
        return true;
    }

    @Override//目标资源运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("运行后运行");
    }

    @Override//渲染后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("渲染后运行");
    }
}
